import React from 'react';
import { Form } from 'antd';
import { FormContainer } from '@/components/UserForm';
import moment from 'moment';
import { DiffContent } from '../../components';

const getBase = base => {
    const title = <div style={{ fontSize: 16, color: '#000', margin: '24px 0', fontWeight: 600 }}>{base.title}</div>;
    const finalValue = { ...base.value };
    // finalValue['实施范围'] = finalValue['实施范围'].slice(0, 1); // 实施范围已去掉
    finalValue['申请日期'] = moment(finalValue['申请日期']).format('YYYY-MM-DD');

    if (finalValue['生效日期'][1] !== '') {
        finalValue['生效日期'] = `${moment(finalValue['生效日期'][1]).format('YYYY-MM-DD')} 起`;
    }

    const cont = (
        <FormContainer>
            {Object.keys(finalValue).map(key => (
                <Form.Item key={key} label={key} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                    {finalValue[key]}
                </Form.Item>
            ))}
        </FormContainer>
    );

    return [title, cont];
};

const getDiffContentData = (formKey, content) => {
    const map = {
        deleteGrade: '删除职级',
        deleteGradeType: '删除职级序列',
        addGrade: '新增职级',
        addGradeType: '新增职级序列'
    };
    const grade = ['职级序列', '职级名称', '职级', '职级定义', '评定维度'];
    const gradeType = ['职级序列', '描述'];
    const isGradeType = formKey.includes('GradeType');
    const keys = isGradeType ? gradeType : grade;
    const contentValue = content.value || {};
    const getLabelValueContent = (labels, receivedValue, beforeOrAfter, isEdit = true, level = 1) => {
        /**
         * 递归函数，返回结构形如 [{ label: '', value },{label:'', value: [{label:'', value: ''}]}]
         */
        const result = [];
        labels.forEach(label => {
            const value = { ...receivedValue };
            let before = value[`修改前${label}`];
            let after = value[label];
            if (label === '职级序列') {
                before = value[`修改前${label}`] || value['修改前职级类别名称'];
                after = value[label] || value['职级类别名称'];
                if (!isGradeType) {
                    before = after;
                }
            }
            if (label === '描述') {
                before = value[`修改前${label}`] || value['修改前职级序列描述'] || value['修改前职级类别描述'];
                after = value[label] || value['职级序列描述'] || value['职级类别描述'];
            }
            const itemValue = beforeOrAfter === 'before' ? before : after;
            const markRed = (data, isLabel = false) => {
                if (isEdit) {
                    return (
                        <span style={{ color: 'red' }}>
                            {data}
                            {isLabel ? '：' : ''}
                        </span>
                    );
                }
                return `${data}${isLabel ? '：' : ''}`;
            };
            const isValueTitle = str => str === '职级描述';
            const getLabels = valueObj => {
                const ret = new Set();
                Object.keys(valueObj).forEach(labelStr => {
                    if (labelStr.indexOf('修改前') > -1) {
                        ret.add(labelStr.slice(3));
                    } else {
                        ret.add(labelStr);
                    }
                });
                return [...ret];
            };
            if (typeof after === 'object' && after !== null) {
                // result.push({
                //     label: `${label}：`,
                //     isValueTitle: isValueTitle(label),
                //     value: getLabelValueContent(getLabels(after), after, beforeOrAfter, 2)
                // });
                result.push(...getLabelValueContent(getLabels(after), after, beforeOrAfter, isEdit, 2));
            } else if (!before && after) {
                if (beforeOrAfter === 'after' || level === 1) {
                    // 新增
                    result.push({
                        label: level === 1 ? `${label}：` : markRed(label, true),
                        isValueTitle: isValueTitle(label),
                        isEdit,
                        level,
                        isChanged: true,
                        value: markRed(itemValue)
                    });
                }
            } else if (before && !after) {
                if (beforeOrAfter === 'before') {
                    // 删除
                    result.push({
                        label: `${label}：`,
                        isValueTitle: isValueTitle(label),
                        isEdit,
                        level,
                        isDeleted: true,
                        value: itemValue
                    });
                } else if (level === 1) {
                    result.push({
                        label: `${label}：`,
                        isValueTitle: isValueTitle(label),
                        isEdit,
                        level,
                        value: itemValue
                    });
                }
            } else if (before && after && before !== after) {
                // 修改
                result.push({
                    label: `${label}：`,
                    isValueTitle: isValueTitle(label),
                    isEdit,
                    level,
                    isChanged: true,
                    value: markRed(itemValue)
                });
            } else {
                // 保持不变
                result.push({
                    label: `${label}：`,
                    level,
                    isEdit,
                    isValueTitle: isValueTitle(label),
                    value: before
                });
            }
        });
        return result;
    };
    const getDimensionValue = () => {
        const result = {};
        if (contentValue['修改前评定维度']) {
            const list = JSON.parse(contentValue['修改前评定维度']);
            if (list.length > 0) {
                list.forEach(item => {
                    result[`修改前${item.dimensionTypeName}`] = item.demand;
                });
            }
        }
        if (contentValue['评定维度']) {
            const list = JSON.parse(contentValue['评定维度']);
            if (list.length > 0) {
                list.forEach(item => {
                    if (item.dimensionTypeName) {
                        result[item.dimensionTypeName] = item.demand;
                    }
                });
            }
        }
        return result;
    };
    const newValue = (() => {
        const allKeys = Object.keys(contentValue);
        const { 修改前评定维度, 评定维度, ...otherValue } = contentValue;
        const result = { ...otherValue };
        if (contentValue['修改前描述'] || contentValue['修改前职级描述']) {
            result['修改前职级定义'] = contentValue['修改前描述'] || contentValue['修改前职级描述'];
        } else if (allKeys.includes('修改前描述') || allKeys.includes('修改前职级描述')) {
            result['修改前职级定义'] = '';
        }
        if (contentValue['描述'] || contentValue['职级描述']) {
            result['职级定义'] = contentValue['描述'] || contentValue['职级描述'];
        }
        result['评定维度'] = getDimensionValue();
        return result;
    })();
    // const origin = getLabelValueContent(keys, newValue, 'before');
    // const updated = getLabelValueContent(keys, newValue, 'after');

    // 新增
    if (formKey.includes('edit')) {
        return [
            { title: '变更前', content: getLabelValueContent(keys, newValue, 'before') },
            { title: '变更后', content: getLabelValueContent(keys, newValue, 'after') }
        ];
    }

    return [{ title: map[formKey], content: getLabelValueContent(keys, newValue, 'after', false) }];
};

const getContent = (content, formKey) => {
    const title = <div style={{ fontSize: 16, color: '#000', margin: '24px 0', fontWeight: 600 }}>{content.title}</div>;
    const contentValue = content.value || {};
    const cont = (
        <>
            <Form.Item label="原因" labelCol={{ span: 3 }} wrapperCol={{ span: 18 }}>
                {contentValue['原因'] || contentValue['变更原因']}
            </Form.Item>
            <Form.Item wrapperCol={{ span: 18, offset: 3 }} style={{ marginTop: 24 }}>
                <DiffContent data={getDiffContentData(formKey, content)} />
            </Form.Item>
        </>
    );

    return [title, cont];
};

export { getBase, getDiffContentData, getContent };
